package com.asa.navigationdempo

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.Navigation
import com.asa.navigationdempo.databinding.FragmentPermissionBinding

class PermissionFragment:Fragment() {


    companion object{
        private val PERMISSIONS_REQUIRED = arrayOf(Manifest.permission.CAMERA)
        private const val PERMISSIONS_REQUEST_CODE = 10

        fun hasPermission(context:Context):Boolean = PERMISSIONS_REQUIRED.all {
            ContextCompat.checkSelfPermission(context,it) == PackageManager.PERMISSION_GRANTED
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (!hasPermission(requireContext())){
            requestPermissions(PERMISSIONS_REQUIRED,PERMISSIONS_REQUEST_CODE)
        }else{
            navigationToCamera()
        }
    }

    private fun navigationToCamera() {
        lifecycleScope.launchWhenStarted {
            Navigation.findNavController(requireActivity(),R.id.fragment_container_view_tag).navigate(PermissionFragmentDirections.actionPermissionToCamera())
        }
    }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return FragmentPermissionBinding.inflate(inflater,container,false).root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PERMISSIONS_REQUEST_CODE){
            if (PackageManager.PERMISSION_GRANTED == grantResults.firstOrNull()){
                Toast.makeText(context, "Permission request granted", Toast.LENGTH_LONG).show()
                navigationToCamera()
            }else{
                Toast.makeText(context, "Permission request denied", Toast.LENGTH_LONG).show()
            }
        }
    }
}